package com.shi.data_structure.queue;

import java.util.Iterator;
import java.util.StringJoiner;

/**
 * 环形链表实现
 * @param <E>
 */
public class LinkedListQueue<E> implements Queue<E>, Iterable<E>{
    /**
     * 节点类
     * @param <E>
     */
    private static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }


    private final Node<E> head = new Node<>(null, null);
    private Node<E> tail = head;
    int size = 0;
    int capacity = Integer.MAX_VALUE;

    //初始化代码块，将构造函数中重复的语句抽取出来
    {
        tail.next = head;
    }

    public LinkedListQueue() {
    }

    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean offer(E value) {
        if(isFull()){
            return false;
        }
        Node<E> added = new Node<>(value,head);
        tail.next = added;
        tail = added;
        size++;
        return false;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        Node<E> first = head.next;
        E value = first.value;
        head.next = first.next;
        if (first == tail){
            tail = head;
        }
        size--;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head.next;
            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }

    @Override
    public String toString() {
        StringJoiner stringJoiner = new StringJoiner(",");
        for (E e : this) {
            stringJoiner.add(e.toString());
        }
        return "[" + stringJoiner.toString() + "]";
    }
}
